<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI MCP客户端测试</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            margin: 0;
            font-size: 2.5em;
            font-weight: 300;
        }
        
        .header p {
            margin: 10px 0 0 0;
            opacity: 0.9;
            font-size: 1.1em;
        }
        
        .content {
            padding: 30px;
        }
        
        .chat-container {
            display: flex;
            flex-direction: column;
            height: 500px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
        }
        
        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #fafafa;
        }
        
        .message {
            margin-bottom: 15px;
            padding: 12px 16px;
            border-radius: 18px;
            max-width: 80%;
            word-wrap: break-word;
        }
        
        .message.user {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            margin-left: auto;
            text-align: right;
        }
        
        .message.ai {
            background: white;
            color: #333;
            border: 1px solid #e0e0e0;
            margin-right: auto;
        }
        
        .message.system {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
            margin: 0 auto;
            text-align: center;
            font-size: 0.9em;
        }
        
        .chat-input {
            display: flex;
            padding: 20px;
            background: white;
            border-top: 1px solid #e0e0e0;
        }
        
        .chat-input input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
        }
        
        .chat-input input:focus {
            border-color: #667eea;
        }
        
        .chat-input button {
            margin-left: 10px;
            padding: 12px 24px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .chat-input button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .chat-input button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            background: #fafafa;
        }
        
        .section h3 {
            margin: 0 0 15px 0;
            color: #333;
            font-size: 1.3em;
        }
        
        .button-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 15px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);
        }
        
        .btn-info {
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
            color: #333;
        }
        
        .btn-info:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(168, 237, 234, 0.4);
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #555;
        }
        
        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            box-sizing: border-box;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
            color: #666;
        }
        
        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .tools-info {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .tools-info h4 {
            margin: 0 0 10px 0;
            color: #1976d2;
        }
        
        .tools-info ul {
            margin: 0;
            padding-left: 20px;
        }
        
        .tools-info li {
            margin-bottom: 5px;
            color: #555;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 AI MCP客户端</h1>
            <p>与AI对话，AI会自动调用MCP客户端工具获取和发送消息</p>
        </div>
        
        <div class="content">
            <!-- 会话管理区域 -->
            <div class="section" style="background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%); border-color: #ffeaa7;">
                <h3>🔑 会话管理</h3>
                <p style="margin: 10px 0; font-size: 14px; color: #856404;">
                    当前会话ID: <strong id="session-id-display" style="color: #667eea;"></strong>
                </p>
                <div class="button-group">
                    <button class="btn btn-success" onclick="resetSession()">🔄 重置会话</button>
                    <button class="btn btn-info" onclick="clearSessionHistory()">🗑️ 清除历史</button>
                </div>
                <p style="margin: 10px 0; font-size: 12px; color: #856404;">
                    💡 提示：同一会话ID可以保持对话上下文，重置会话后将开始全新的对话
                </p>
            </div>
            
            <!-- AI工具信息 -->
            <div class="tools-info">
                <h4>🛠️ AI可用工具</h4>
                <ul>
                    <li><strong>getAllConversations</strong> - 获取所有聊天记录列表</li>
                    <li><strong>getConversationById</strong> - 根据ID获取特定聊天记录</li>
                    <li><strong>getMessagesByConversationId</strong> - 获取指定会话的消息列表</li>
                    <li><strong>sendMessage</strong> - 向指定会话发送消息</li>
                    <li><strong>pingMcpServer</strong> - 测试MCP服务器连接状态</li>
                    <li><strong>checkMcpHealth</strong> - 检查MCP客户端健康状态</li>
                </ul>
            </div>
            
            <!-- 聊天界面 -->
            <div class="section">
                <h3>💬 AI聊天</h3>
                <p>直接与AI对话，AI会根据你的需求自动调用相应的MCP工具</p>
                
                <div class="chat-container">
                    <div class="chat-messages" id="chatMessages">
                        <div class="message system">
                            🤖 你好！我是AI助手，可以帮你管理聊天记录和消息。你可以直接告诉我你想要做什么，我会自动调用相应的工具。
                        </div>
                    </div>
                    
                    <div class="chat-input">
                        <input type="text" id="messageInput" placeholder="输入你的消息，例如：请帮我获取所有聊天记录" />
                        <button id="sendButton" onclick="sendMessage()">发送</button>
                    </div>
                </div>
            </div>
            
            <!-- 快速测试 -->
            <div class="section">
                <h3>🧪 快速测试</h3>
                <p>点击下面的按钮快速测试AI工具调用</p>
                <div class="button-group">
                    <button class="btn btn-primary" onclick="testGetConversations()">获取聊天记录</button>
                    <button class="btn btn-success" onclick="testSendMessage()">发送测试消息</button>
                    <button class="btn btn-info" onclick="testPing()">Ping测试</button>
                    <button class="btn btn-primary" onclick="clearChat()">清空聊天</button>
                </div>
            </div>
            
            <!-- 加载指示器 -->
            <div id="loading" class="loading">
                <div class="spinner"></div>
                <div>AI正在思考中...</div>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = '/api/ai-mcp';
        
        // 生成唯一的会话ID（使用 localStorage 持久化）
        let sessionId = localStorage.getItem('ai-mcp-session-id');
        if (!sessionId) {
            sessionId = 'ai-mcp-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
            localStorage.setItem('ai-mcp-session-id', sessionId);
        }
        
        console.log('🔑 当前会话ID:', sessionId);
        
        // 显示加载状态
        function showLoading() {
            document.getElementById('loading').style.display = 'block';
        }
        
        // 隐藏加载状态
        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
        }
        
        // 重置会话（生成新的 sessionId）
        function resetSession() {
            sessionId = 'ai-mcp-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
            localStorage.setItem('ai-mcp-session-id', sessionId);
            document.getElementById('session-id-display').textContent = sessionId;
            console.log('🔄 会话已重置，新会话ID:', sessionId);
            
            // 清空聊天界面
            const messagesContainer = document.getElementById('chatMessages');
            messagesContainer.innerHTML = '<div class="message system">✅ 会话已重置！新会话ID: ' + sessionId + '<br><br>现在你可以开始一个全新的对话了</div>';
        }
        
        // 清除当前会话的历史记录
        async function clearSessionHistory() {
            try {
                const response = await fetch(`/api/chat/clear-history?sessionId=${sessionId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                
                const data = await response.json();
                
                if (data.success) {
                    addMessage('✅ ' + data.response, 'system');
                } else {
                    addMessage('❌ 清除失败: ' + (data.error || '未知错误'), 'system');
                }
            } catch (error) {
                addMessage('❌ 清除失败: ' + error.message, 'system');
            }
        }
        
        // 添加消息到聊天界面
        function addMessage(content, type = 'ai') {
            const messagesContainer = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            messageDiv.textContent = content;
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
        
        // 发送消息
        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message) return;
            
            // 显示用户消息
            addMessage(message, 'user');
            input.value = '';
            
            showLoading();
            
            try {
                const response = await fetch(`${API_BASE}/chat`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message,
                        sessionId: sessionId
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 处理AI响应，如果包含工具调用信息，提取实际内容
                    let aiResponse = data.response;
                    if (aiResponse && aiResponse.includes('tool_calls')) {
                        // 如果响应包含工具调用信息，显示更友好的消息
                        addMessage('AI正在调用MCP工具获取数据...', 'system');
                        // 可以在这里添加一个延迟，然后显示实际结果
                        setTimeout(() => {
                            addMessage('工具调用完成，请查看服务器日志获取详细信息', 'ai');
                        }, 1000);
                    } else {
                        addMessage(aiResponse, 'ai');
                    }
                } else {
                    addMessage(`错误: ${data.error}`, 'system');
                }
                
            } catch (error) {
                addMessage(`网络错误: ${error.message}`, 'system');
            } finally {
                hideLoading();
            }
        }
        
        // 测试获取聊天记录
        async function testGetConversations() {
            const input = document.getElementById('messageInput');
            input.value = '请帮我获取所有聊天记录';
            await sendMessage();
        }
        
        // 测试发送消息
        async function testSendMessage() {
            const input = document.getElementById('messageInput');
            input.value = '请帮我发送一条测试消息到会话1';
            await sendMessage();
        }
        
        // 测试Ping
        async function testPing() {
            const input = document.getElementById('messageInput');
            input.value = '请检查MCP服务器连接状态';
            await sendMessage();
        }
        
        // 清空聊天
        function clearChat() {
            const messagesContainer = document.getElementById('chatMessages');
            messagesContainer.innerHTML = '<div class="message system">🤖 聊天已清空，请继续与我对话！</div>';
        }
        
        // 回车发送消息
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
        
        // 页面加载完成后的欢迎消息
        window.onload = function() {
            // 显示会话ID
            document.getElementById('session-id-display').textContent = sessionId;
            
            setTimeout(() => {
                addMessage('💡 提示: 你可以直接说"获取所有聊天记录"、"发送消息"、"检查连接状态"等，我会自动调用相应的工具！', 'system');
            }, 1000);
        };
    </script>
</body>
</html>
